import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';

/// 响应拦截，对数据进行过滤
class NormalInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    print("NormalInterceptor onRequest:: ${options.uri} ");
    handler.next(options);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print("NormalInterceptor onError:: ${err.message} ");
    formatError(err);
    handler.reject(err);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    print("NormalInterceptor onResponse:: ${response.data} ");
    handler.resolve(response);
  }

  /// error统一处理
  void formatError(DioError err) {
    var errorHashCode = err.hashCode.toString();
    var errorType = err.runtimeType;
    try {
      DioErrorType type = errorType as DioErrorType;
      switch (type) {
        case DioErrorType.connectTimeout:
          print(errorHashCode + " 连接超时");
          break;
        case DioErrorType.sendTimeout:
          print(errorHashCode + " 请求超时");
          break;
        case DioErrorType.receiveTimeout:
          print(errorHashCode + " 响应超时");
          break;
        case DioErrorType.response:
          print(errorHashCode + " 出现404 503");
          break;
        case DioErrorType.cancel:
          print(errorHashCode + " 连接取消");
          break;
        default:
          print("message = ${err.message}");
          break;
      }
    } catch (e) {
      print(e);
    }
  }
}
